package org.iabako.client.ui.form.business.paymentrequest;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.ui.HTMLPanel;
import org.iabako.client.config.page.PageConfigEnum;
import org.iabako.client.config.page.PageEnum;
import org.iabako.client.navigation.NavigationController;
import org.iabako.client.tools.IabakoAsyncCallback;
import org.iabako.client.tools.Messages;
import org.iabako.client.ui.form.AbstractForm;
import org.iabako.client.ui.layout.field.CheckboxBoolean;
import org.iabako.client.ui.layout.field.IField;
import org.iabako.client.ui.layout.field.InputTextInteger;
import org.iabako.client.ui.layout.field.LabelText;
import org.iabako.client.ui.layout.template.Popup;
import org.iabako.client.ui.layout.widget.dialogbox.IabakoDialogBox;
import org.iabako.client.ui.layout.widget.validation.ValidationMessage;
import org.iabako.shared.entity.business.AbstractEntity;
import org.iabako.shared.entity.business.PaymentRequestConfig;
import org.iabako.shared.iservice.business.PaymentRequestServiceAsync;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by jose on 29/01/15.
 */
public class PaymentRequestConfigForm extends AbstractForm {

    interface MyUiBinder extends UiBinder<HTMLPanel, PaymentRequestConfigForm> {
    }

    protected MyUiBinder binderForm = GWT.create(MyUiBinder.class);

    protected final PaymentRequestServiceAsync paymentRequestServiceAsync = PaymentRequestServiceAsync.Util.getInstance();

    @UiField
    CheckboxBoolean paymentRequestBefore;
    @UiField
    CheckboxBoolean paymentRequestAfter;
    @UiField
    HTMLPanel paymentRequestBeforePanel;
    @UiField
    HTMLPanel paymentRequestAfterPanel;
    @UiField
    InputTextInteger daysBefore;
    @UiField
    InputTextInteger daysAfter;
    @UiField
    LabelText seeBeforeMailContent;
    @UiField
    LabelText seeAfterMailContent;

    int daysBeforePaymentFromDB;
    int daysAfterPaymentFromDB;

    public PaymentRequestConfigForm(PageConfigEnum pageConfigEnum) {
        setForm(binderForm, pageConfigEnum, "");
        Popup.resizeToSmallPopup();

        setHandlers();

        setDefaultValues();
    }

    private void setDefaultValues() {
        daysBefore.setValue("5");
        daysAfter.setValue("5");
    }

    private void setHandlers() {
        paymentRequestBefore.getCheckbox().addClickHandler(new ClickHandler() {
            public void onClick(ClickEvent event) {
                paymentRequestBeforePanel.setVisible(paymentRequestBefore.getValue());
            }
        });
        paymentRequestAfter.getCheckbox().addClickHandler(new ClickHandler() {
            public void onClick(ClickEvent event) {
                paymentRequestAfterPanel.setVisible(paymentRequestAfter.getValue());
            }
        });

        final PaymentRequestConfigForm parentForm = this;

        seeBeforeMailContent.getLabel().addClickHandler(new ClickHandler() {
            public void onClick(ClickEvent event) {
                NavigationController.getInstance().goTo(PageEnum.PaymentRequestMail, parentForm, "before");
            }
        });

        seeAfterMailContent.getLabel().addClickHandler(new ClickHandler() {
            public void onClick(ClickEvent event) {
                NavigationController.getInstance().goTo(PageEnum.PaymentRequestMail, parentForm, "after'");
            }
        });
    }

    @Override
    protected List<IField> getMandatoryFields() {
        List<IField> mandatoryFields = new ArrayList<IField>();

        if (paymentRequestBefore.getValue()) {
            mandatoryFields.add(daysBefore);
        }

        if (paymentRequestAfter.getValue()) {
            mandatoryFields.add(daysAfter);
        }
        return mandatoryFields;
    }

    protected void setPaymentRequestConfig(PaymentRequestConfig paymentRequestConfig) {

        entity = paymentRequestConfig;
        daysBeforePaymentFromDB = paymentRequestConfig.getDaysBeforePayment();
        daysAfterPaymentFromDB = paymentRequestConfig.getDaysAfterPayment();

        if (paymentRequestConfig.getDaysBeforePayment() >= 0) {
            paymentRequestBefore.setValue(true);
            paymentRequestBeforePanel.setVisible(true);
            daysBefore.setValue(paymentRequestConfig.getDaysBeforePayment() + "");
        }

        if (paymentRequestConfig.getDaysAfterPayment() >= 0) {
            paymentRequestAfter.setValue(true);
            paymentRequestAfterPanel.setVisible(true);
            daysAfter.setValue(paymentRequestConfig.getDaysAfterPayment() + "");
        }
    }

    @Override
    protected AbstractEntity getEntity() {
        if (entity == null) {
            entity = new PaymentRequestConfig();
        }
        PaymentRequestConfig paymentRequestConfig = (PaymentRequestConfig) entity;

        if (paymentRequestBefore.getValue()) {
            paymentRequestConfig.setDaysBeforePayment(daysBefore.getIntValue());
        } else {
            paymentRequestConfig.setDaysBeforePayment(-1);
        }

        if (paymentRequestAfter.getValue()) {
            paymentRequestConfig.setDaysAfterPayment(daysAfter.getIntValue());
        } else {
            paymentRequestConfig.setDaysAfterPayment(-1);
        }
        return paymentRequestConfig;
    }

    public PaymentRequestConfig getPaymentRequestConfig() {
        return (PaymentRequestConfig) entity;
    }

    @Override
    public boolean validate() {
        if (!uiValidation()) {
            return false;
        }

        if (daysBefore.getIntValue() == 0 && daysAfter.getIntValue() == 0) {
            ValidationMessage.getFirstFromDOM().showErrorMessage(true, true, "payment_request_validation_same_day_error");
            return false;
        }

        final PaymentRequestConfig paymentRequestConfig = (PaymentRequestConfig) serverValidation();
        if (paymentRequestConfig == null) {
            return false;
        }

        if (daysBeforePaymentFromDB == paymentRequestConfig.getDaysBeforePayment() && daysAfterPaymentFromDB == paymentRequestConfig.getDaysAfterPayment()) {
            //No modifications
            popup.handleClickClose();
            return true;
        }

        if(paymentRequestConfig.getDaysBeforePayment() == -1 && paymentRequestConfig.getDaysAfterPayment() == -1){
            //Total disable
            savePaymentRequestConf(paymentRequestConfig);
            return true;
        }

        paymentRequestServiceAsync.getNumberOfInstallmentsForRequestBetween(paymentRequestConfig, new IabakoAsyncCallback<List<Integer>>() {
            public void onSuccess(List<Integer> result) {

                String confirmMessage = Messages.getLabel("payment_request_modification_confirm_text", result.get(0) + "", result.get(1) + "");

                IabakoDialogBox iabakoDialogBox = new IabakoDialogBox("payment_request_modification_confirm_title", confirmMessage, true, "payment_request_modification_confirm_ok") {
                    @Override
                    protected void customConfirmButtonHandler() {
                        savePaymentRequestConf(paymentRequestConfig);
                    }
                };
                iabakoDialogBox.setCloseOnlySimplePopup(true);

                NavigationController.getInstance().show(iabakoDialogBox);

                super.onSuccess(result);
            }
        });

        return false;
    }

    private void savePaymentRequestConf(PaymentRequestConfig paymentRequestConfig) {

        paymentRequestServiceAsync.save(paymentRequestConfig, new IabakoAsyncCallback<PaymentRequestConfig>() {

            public void onSuccess(PaymentRequestConfig result) {
                popup.handleClickClose();
                ValidationMessage.getFromRootPage().showSuccessMessage("validation_payment_request_save_success");
                super.onSuccess(result);
            }
        });
    }
}
